home *** CD-ROM | disk | FTP | other *** search
/ Aminet 30 / Aminet 30 (1999)(Schatztruhe)[!][Apr 1999].iso / Aminet / hard / hack / i2clib40.lha / i2clib40 / src / ReceiveI2C.c < prev    next >
C/C++ Source or Header  |  1997-03-28  |  2KB  |  63 lines

  1. /* ReceiveI2C.c: 
  2.  *   Copy bytes from the I²C bus to stdout, using i2c.library.  Usage:
  3.  * ReceiveI2C  <bus address>  <number of bytes>
  4.  * where <bus address> is hex, <number of bytes> is a decimal number.
  5.  */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <proto/exec.h>
  11. #include <proto/i2c.h>
  12. #include <libraries/i2c.h>
  13.  
  14. struct Library *I2C_Base;
  15.  
  16. int main(int argc, char *argv[])
  17. {
  18.   int c, result=0, binary=0;
  19.   size_t i, bytes;
  20.   UBYTE adr, *i2cdata;
  21.   ULONG err;
  22.  
  23.   if (argc<3) {
  24.     fprintf(stderr, "Usage: \e[2m%s <addr> <bytes> [-b]\e[0m, "
  25.         "e.g. %s 20 5\n", argv[0], argv[0]);
  26.     return 5;
  27.   }
  28.   adr = strtoul(argv[1], NULL, 16);
  29.   bytes = atol(argv[2]);
  30.   if (argc>3 && strncmp(argv[3], "-b", 2)==0)
  31.     binary = 1;
  32.   i2cdata = malloc(bytes);
  33.   if (!i2cdata) {
  34.     fprintf(stderr, "Out of memory (%ld bytes)\n", bytes);
  35.     return 10;
  36.   }
  37.   I2C_Base = OpenLibrary("i2c.library", 39);
  38.   if (!I2C_Base) {
  39.     fprintf(stderr, "Can't open i2c.library V39+\n");
  40.     free(i2cdata);
  41.     return 10;  
  42.   }
  43.   err = ReceiveI2C(adr, bytes, i2cdata);
  44.   if ((err & 0xff)==0) {
  45.     fprintf(stderr, "I²C failure: \e[1m%s\e[0m\n", I2CErrText(err));
  46.     result = 10;
  47.   } else for (i=0; i<bytes; i++) {
  48.     if (binary)
  49.       putchar(i2cdata[i]);
  50.     else {
  51.       printf("%02X", i2cdata[i]);
  52.       c = ((i%4)==3) ? ' ' : '\0';
  53.       if ((i%32)==31 || i==bytes-1)  c = '\n';
  54.       if (c)  putchar(c);
  55.     }     
  56.   }
  57.   CloseLibrary(I2C_Base);
  58.   free(i2cdata);
  59.  
  60.   return result;
  61. }
  62.  
  63.